<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小企业实现低成本数字化转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82282996  15899929162
// +----------------------------------------------------------------------
namespace app\controller\property\energy;

use think\App;
use app\controller\property\Base;
use app\validate\energy\EnergyBillValidate;
use app\common\repositories\bill\BillBasicRepository;
use app\common\repositories\energy\EnergyPlanRepository;
use app\common\repositories\energy\EnergyBillRepository;
use app\common\repositories\energy\EnergyMeterRepository;
use app\common\repositories\property\basic\PropertyBasicRepository;


class EnergyBill extends Base
{
    protected $repository;

    public function __construct(App $app, EnergyBillRepository $repository)
    {
        parent::__construct($app);
        $this->repository = $repository;
        $this->assign([
            'addAuth' => property_auth('propertyEnergyBillAdd'),
            'editAuth' => property_auth('propertyEnergyBillEdit'),
            'delAuth' => property_auth('propertyEnergyBillDel'),
            'detailAuth' => property_auth('propertyEnergyBillDetail'),
        ]);
    }

    protected function commonParams()
    {
        /** @var EnergyMeterRepository $energyMeterRepository */
        $energyMeterRepository = app()->make(EnergyMeterRepository::class);
        $energyTypeData = $energyMeterRepository::ENERGY_TYPE;
        $this->assign([
            'energyTypeData' => $energyTypeData,
        ]);
    }

    public function list()
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'energy_type' => '',
                'energy_no' => '',
                'keywords' => '',
            ]);
            [$page, $limit] = $this->getPage();
            $data = $this->repository->getpropertyList($where, $page, $limit, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $data['list'], 'count' => $data['count']]);
        }
        $this->commonParams();
        return $this->fetch('energy/bill/list');
    }

    public function add()
    {
        if ($this->request->isAjax() && $this->request->get('get_type') == 'getEnergyMeterInfo') {
            $energyId = (int)$this->request->param('energy_id');
            /** @var EnergyMeterRepository $energyMeterRepository */
            $energyMeterRepository = app()->make(EnergyMeterRepository::class);
            $meterInfoData = $energyMeterRepository->getDetail($energyId);
            return json()->data(['code' => 0, 'data' => $meterInfoData]);
        } else if ($this->request->isPost()) {
            $param = $this->request->param([
                'energy_id' => '',
                'is_settle' => '',
                'start_num_z' => '',
                'end_num_z' => '',
                'start_num_j' => '',
                'end_num_j' => '',
                'start_num_f' => '',
                'end_num_f' => '',
                'start_num_p' => '',
                'end_num_p' => '',
                'start_num_g' => '',
                'end_num_g' => '',
                'remark' => '',
                'bill_number' => '',
            ]);
            validate(EnergyBillValidate::class)->scene('add')->check($param);

            /** @var BillBasicRepository $billBasicRepository */
            $billBasicRepository = app()->make(BillBasicRepository::class);
            $billId = $billBasicRepository->getSearch(['number' => $param['bill_number']])->value('id');
            if ($billId <= 0) {
                return $this->error($param['bill_number'] . ' 账单编号不在存');
            }
            $param['bill_id'] = $billId;
            try {
                $res = $this->repository->addInfo($this->request->propertyId, $param, $this->request->userId);
                if ($res) {
                    return $this->success('添加成功');
                } else {
                    return $this->error('添加失败');
                }
            } catch (\Exception $e) {
                exception_log('添加能源账单失败', $e);
                return $this->error('网络错误');
            }
        } else {
            $this->commonParams();
            /** @var EnergyMeterRepository $energyMeterRepository */
            $energyMeterRepository = app()->make(EnergyMeterRepository::class);
            $meterListData = $energyMeterRepository->getSearch([])
                ->where('property_id', $this->request->propertyId)
                ->field('id,energy_name')
                ->select()->toArray();
            return $this->fetch('energy/bill/add', [
                'meterListData' => $meterListData
            ]);
        }

    }

    public function edit()
    {
        $id = (int)$this->request->param('id');
        if (!$id) {
            return $this->error('参数错误');
        }
        $info = $this->repository->getDetail($id);
        if (!$info) {
            return $this->error('信息错误');
        }
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'is_settle' => '',
                'start_num_z' => '',
                'end_num_z' => '',
                'start_num_j' => '',
                'end_num_j' => '',
                'start_num_f' => '',
                'end_num_f' => '',
                'start_num_p' => '',
                'end_num_p' => '',
                'start_num_g' => '',
                'end_num_g' => '',
                'remark' => '',
            ]);
            validate(EnergyBillValidate::class)->scene('edit')->check($param);
            try {
                $res = $this->repository->editInfo($info, $param, $this->request->userId);
                if ($res) {
                    return $this->success('修改成功');
                } else {
                    return $this->error('修改失败');
                }
            } catch (\Exception $e) {
                exception_log('编辑能源账单失败', $e);
                return $this->error('网络错误');
            }
        } else {
            /** @var EnergyPlanRepository $planRepository */
            $planRepository = app()->make(EnergyPlanRepository::class);
            $planData = $planRepository->getSearch([])
                ->where('property_id', $info['property_id'])
                ->field('id,plan_name')
                ->select()->toArray();
            $this->commonParams();
            return $this->fetch('energy/bill/edit', [
                'info' => $info,
                'planData' => $planData,
            ]);
        }
    }


    public function detail()
    {
        $meterId = (int)$this->request->param('meter_id');
        if ($meterId <= 0) {
            return $this->error('参数错误');
        }
        $info = $this->repository->getDetail($meterId);
        if ($info['id'] <= 0) {
            return $this->error('方案不存在');
        }
        return $this->fetch('energy/bill/detail', [
            'info' => $info,
        ]);
    }


    public function del()
    {
        $ids = (array)$this->request->param('ids');
        try {
            $data = $this->repository->batchDelete($ids);
            if ($data) {
                return $this->success('删除成功');
            } else {
                return $this->error('删除失败');
            }
        } catch (\Exception $e) {
            exception_log('删除能源账单失败', $e);
            return $this->error('网络失败');
        }
    }


}